package com.echo.yixiaowu.feature.player

import android.annotation.SuppressLint
import android.app.Activity
import android.content.res.Configuration
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.material3.Text
import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import com.echo.yixiaowu.data.model.player.CardContentType
import com.echo.yixiaowu.data.model.player.CardDetailItemData
import com.echo.yixiaowu.feature.components.LandscapeVideoPlayer
import com.echo.yixiaowu.feature.components.PortraitVideoPlayerPage
import com.echo.yixiaowu.feature.components.VideoPlayerContainer
import com.echo.yixiaowu.feature.components.rememberIsAutoRotateEnabled
import com.echo.yixiaowu.main.findActivity
import com.echo.yixiaowu.route.AppRoute
import com.echo.yixiaowu.util.SystemUtil
import com.echo.yixiaowu.util.SystemUtil.isOrientationPortrait
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.datetime.Clock
import kotlin.math.roundToInt
import kotlin.random.Random

/**
 * 媒体界面
 */
@SuppressLint("ConfigurationScreenWidthHeight")
@OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
@Composable
fun MediaPage(
    param: AppRoute.Detail,
    navController: NavHostController,
    viewModel: MediaViewModel = viewModel()
) {
    val scope = rememberCoroutineScope()
    val context = LocalContext.current
    val activity = context.findActivity()
    val density = LocalDensity.current
    val configuration: Configuration = LocalConfiguration.current
    val windowSizeClass = calculateWindowSizeClass(context as Activity)
    val isOrientationPortrait = isOrientationPortrait()
    val widthSizeClass = windowSizeClass.widthSizeClass
    val heightSizeClass = windowSizeClass.heightSizeClass
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    val mediaUiState by viewModel.mediaUiState.collectAsStateWithLifecycle()
    val isAutoRotateEnabled by rememberIsAutoRotateEnabled()
    val media = viewModel.mediaController.collectAsStateWithLifecycle()
    val systemBarHeight: Dp = SystemUtil.getSystemBarHeightDp(density)

    val itemData = uiState.itemData
    val mediaController = media.value
    var lastTapTime by remember { mutableLongStateOf(0) }
    fun resetHideControlTimer() {
        lastTapTime = Clock.System.now().toEpochMilliseconds()
    }

    fun hideControl() {
        if (!mediaUiState.isShowControl) return
        scope.launch {
            delay(5500)
            val currentTime = Clock.System.now().toEpochMilliseconds()
            if (currentTime - lastTapTime > 5000) {
                viewModel.processIntent(MediaPageIntent.SetControlVisible(false))
            }
        }
    }

    LaunchedEffect(mediaUiState.isShowControl) {
        hideControl()
    }

    LaunchedEffect(param.itemId) {
        viewModel.initializePlayer(context)
        viewModel.processIntent(MediaPageIntent.LoadItemData(param.itemId))
        viewModel.initializeScreenState(
            when {
                isOrientationPortrait -> configuration.screenHeightDp + systemBarHeight.value.roundToInt()
                else -> configuration.screenWidthDp + systemBarHeight.value.roundToInt()
            },
            when {
                isOrientationPortrait -> configuration.screenWidthDp
                else -> configuration.screenHeightDp
            },
            mediaUiState.width, mediaUiState.height
        )
    }

    LaunchedEffect(mediaUiState.width, mediaUiState.height) {
        viewModel.computeScreenSize(mediaUiState.width, mediaUiState.height)
    }


    if (uiState.fetchDataState.isLoading) {
        when (param.itemType) {
            CardContentType.VIDEO.toString() -> VideoDetailSkeleton()
            CardContentType.TEXT.toString() -> TextImageDetailSkeleton()
        }
    } else if (uiState.fetchDataState.error != null) {
        ErrorDetailSkeleton()
    } else {
        if (itemData is CardDetailItemData.VideoItem) {
            VideoPlayerContainer(
                itemData = itemData,
                viewModel = viewModel,
                isFullScreen = mediaUiState.isFullScreen,
                activity = activity,
                navController = navController,
                mediaController = mediaController
            ) { player ->
                if (widthSizeClass == WindowWidthSizeClass.Compact) {
                    PortraitVideoPlayerPage(
                        navController = navController,
                        item = itemData,
                        resetHideControlTimer = ::resetHideControlTimer,
                        mediaState = mediaUiState,
                        mediaController = mediaController,
                        player = player,
                        onIntent = viewModel::processIntent
                    )
                } else {
                    // --- 横屏播放器 ---
                    LandscapeVideoPlayer(
                        navController = navController,
                        itemData = itemData,
                        resetHideControlTimer = ::resetHideControlTimer,
                        mediaState = mediaUiState,
                        isAutoRotateEnabled = isAutoRotateEnabled,
                        mediaController = mediaController!!,
                        player = player,
                        onIntent = viewModel::processIntent
                    )
                }
            }
        } else {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color.Gray),
                contentAlignment = Alignment.Center
            ) {
                Text("${Random.nextInt(0, 1000)}")
            }
        }
    }
}

@Composable
fun VideoDetailSkeleton() {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black)
            .statusBarsPadding(),
        contentAlignment = Alignment.Center
    ) {
        Box(
            modifier = Modifier
                .fillMaxHeight()
                .height(250.dp)
        )
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(top = 230.dp)
                .background(Color.White)
        )
    }
}

@Composable
fun TextImageDetailSkeleton() {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Gray),
        contentAlignment = Alignment.Center
    ) {
        Text("假装是文本骨架屏")
    }
}

@Composable
fun ErrorDetailSkeleton() {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Gray),
        contentAlignment = Alignment.Center
    ) {
        Text("加载错误")
    }
}